const check_password = (rule: any, value: any, callback: any) => {
  if (value.length < 8 || value.length > 16) {
    return new Promise((resolve, reject) => {
      reject("密码长度为8-16位");
    });
  }
  return Promise.resolve();
};

const check_32_bytes_string = (rule: any, value: any, callback: any, notice: any) => {
  const reg = new RegExp("[\u4E00-\u9FA5]+");
  let count = 0;
  for (let i = 0; i < value.length; i++) {
    if (reg.test(value[i])) {
      count = count + 3;
    } else {
      count = count + 1;
    }
  }

  if (count > 32 || count === 0) {
    return new Promise((resolve, reject) => {
      reject(notice);
    });
  }
  return Promise.resolve();
};

const check_mac_format = (
  _: any,
  value: string,
  { field, existingMacs = [] }: { 
    field?: string;
    existingMacs?: string[] 
  } = {}
) => {
  const splitRegex = field === 'singleMac' ? /[,\s]+/ : '\n';
  const macs = value.split(splitRegex)
    .filter(v => v.trim())
    .map(m => m.trim().toUpperCase());

  // 格式验证
  const invalidMacs = macs.filter(mac => 
    !/^([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2})$/.test(mac)
  );

  if (invalidMacs.length > 0) {
    return Promise.reject(
      `第${invalidMacs.map(m => macs.indexOf(m)+1).join(',')}行MAC格式错误`
    );
  }

  // 检查输入内容自身的重复项
  const macSet = new Set();
  const duplicateEntries = macs.filter(mac => {
    const exists = macSet.has(mac);
    macSet.add(mac);
    return exists;
  });

  if (duplicateEntries.length > 0) {
    const duplicatePositions = Array.from(new Set(duplicateEntries))
      .map(mac => macs.indexOf(mac) + 1);
    return Promise.reject(
      `第${duplicatePositions.join(',')}行存在重复MAC地址`
    );
  }

  // 单MAC字段重复校验
  if (field === 'singleMac') {
    const duplicates = macs.filter(m => existingMacs.includes(m));
    if (duplicates.length > 0) {
      return Promise.reject(
        `MAC地址重复：${duplicates.join(', ')}`
      );
    }
  }

  return Promise.resolve();
};

export { check_password, check_32_bytes_string, check_mac_format };
